package cn.afactory.tygz.ui.user;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.tendcloud.tenddata.TCAgent;

import cn.afactory.tygz.R;
import cn.afactory.tygz.TianYaGongZaiApplication;
import cn.afactory.tygz.model.UserInfo;
import cn.afactory.tygz.net.NetManager;
import cn.afactory.tygz.net.lsn.OnResponseListener;
import cn.afactory.tygz.ui.MainActivity;
import cn.afactory.tygz.ui.base.BaseActivity;
import cn.afactory.tygz.ui.base.utils.DialogUtil;
import cn.afactory.tygz.ui.base.utils.LoadingDialog;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.base.utils.sns.Tools;


/**
 * Created with Android Studio.
 * Title:RegisterActivity
 * Description:
 * Copyright:Copyright (c) 2014
 * Company:中国平安健康保险有限公司
 * Author:Alice
 * Date:15/9/2
 * Time:下午5:30
 * Version 1.0
 */
public class RegisterActivity extends BaseActivity {
    private static final int MSG_TIMER = 1;
    private static final int MSG_SHOW_TOAST = 0x1003;
    private static final int MSG_VERIFY_FAILD = 0x1005;
    private static final int MSG_VERIFY_OK = 0x10031;
    private static final int MSG_REGISTER_REAL = 0x1009;

    private Context context;
    private EditText mPhoneNumberEditText;
    private EditText mVerifyCodeEt;
    private EditText mPasswordEt;
    private TextView mBtnRegister;
    private boolean mHasSendCode = false;
    boolean isRequestingDynamicCode = false;

    /** @Fields isVerifyCodeTime: 是否在60秒时间内*/
    private boolean isVerifyCodeTime = false;
    private TextView mSendReqcodeBtn;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;

        setContentView(R.layout.ac_register);

        setTitleText("注册");
        initUI();
    }

    /**
     * 跳转到个人信息手机页面
     */
    private void gotoUserInfoCollection(){
        startActivity(new Intent(this, UserInfoCollectionActivity.class));
    }

    @Override
    protected void onResume() {
        super.onResume();
        TCAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        TCAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.right_in, R.anim.left_out);
    }

    private void initUI() {
        mPhoneNumberEditText = (EditText) findViewById(R.id.phone_number_edit);
        mPhoneNumberEditText
                .setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId,
                                                  KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE
                                || actionId == EditorInfo.IME_ACTION_SEND
                                || actionId == EditorInfo.IME_ACTION_GO
                                || actionId == EditorInfo.IME_ACTION_SEARCH
                                || actionId == EditorInfo.IME_ACTION_NEXT
                                || actionId == EditorInfo.IME_ACTION_PREVIOUS) {
                            doRegister();
                            return true;
                        }
                        return false;
                    }
                });

        mPasswordEt = (EditText)findViewById(R.id.password_edit);
        mVerifyCodeEt = (EditText)findViewById(R.id.verify_code_et);

        mBtnRegister = (TextView)findViewById(R.id.btn_register);
        mBtnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doRegister();
            }
        });

        mSendReqcodeBtn = (TextView)findViewById(R.id.send_reqcode_btn);
        mSendReqcodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doReqSmsCode();
            }
        });

        mPhoneNumberEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showLoginButton();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mVerifyCodeEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showLoginButton();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mPasswordEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showLoginButton();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        showLoginButton();

//        mPhoneNumberEditText.setText("18616312232");
//        mVerifyCodeEt.setText("888888");
//        mPasswordEt.setText("123456");
    }

    private String getLastPhoneNumber() {
        return SPUtils.getMobilePhone(this);
    }

    private void showLoginButton(){
        if(!TextUtils.isEmpty(mPhoneNumberEditText.getText().toString())
                && !TextUtils.isEmpty(mPasswordEt.getText().toString())
                && !TextUtils.isEmpty(mVerifyCodeEt.getText().toString())) {
            mBtnRegister.setClickable(true);
            mBtnRegister.setEnabled(true);
            mBtnRegister.setPressed(true);
            mBtnRegister.setBackgroundResource(R.drawable.btn_rect_orange_fill);
        } else {
            mBtnRegister.setClickable(false);
            mBtnRegister.setEnabled(false);
            mBtnRegister.setPressed(false);
            mBtnRegister.setBackgroundResource(R.drawable.btn_rect_orange_fill_disable);
        }
    }

    private LoadingDialog loadingDialog;
    protected void showLoadingDialog(String msg) {
        if (loadingDialog == null) {
            loadingDialog = DialogUtil.showLoadingDialog(this, msg, true);
        }
        if (!TextUtils.isEmpty(msg)) {
            loadingDialog.setDlgMessage(msg);
        }
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    protected void hideLoadingDialog() {
        if (!isFinishing() && loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_SHOW_TOAST:
                hideLoadingDialog();
                LocalUtils.showToast(context, (String) msg.obj);
                break;
            case MSG_VERIFY_FAILD:
                hideLoadingDialog();
                showErrorMsg(R.string.toast_query_sms_failed);
                break;
            case MSG_VERIFY_OK:
                hideLoadingDialog();
                break;
            case MSG_REGISTER_REAL:
                doRegister();
                break;
            case MSG_TIMER:
                if (msg.arg1 > 0) {
                    setVerifyCodeTime(msg.arg1-1);
                    sendTime(msg.arg1-1);
                } else {
                    setVerifyCodeTime(0);
                    mSendReqcodeBtn.setEnabled(true);
                    showSendReqButton();
                    mSendReqcodeBtn.setTextColor(getResources().getColor(R.color.white));
                }
                break;
        }
    }

    /**
     * 更新发送短信验证码的状态
     */
    private void showSendReqButton(){
        if(isVerifyCodeTime){
            return;
        }
        if(TextUtils.isEmpty(mPhoneNumberEditText.getText().toString())){
            mSendReqcodeBtn.setEnabled(false);
            mSendReqcodeBtn.setBackgroundResource(R.drawable.btn_rect_orange_fill_disable);
            mSendReqcodeBtn.setTextColor(Color.WHITE);
        } else {
            mSendReqcodeBtn.setEnabled(true);
            mSendReqcodeBtn.setBackgroundResource(R.drawable.btn_rect_orange_fill);
            mSendReqcodeBtn.setTextColor(getResources().getColor(R.color.white));
        }
    }

    private void showErrorMsg(String msg) {
        Message.obtain(mUIHandler,MSG_SHOW_TOAST, msg).sendToTarget();
    }

    private void showErrorMsg(int resId) {
        Message.obtain(mUIHandler,MSG_SHOW_TOAST, getString(resId)).sendToTarget();
    }


    private String dynamicCode;
    private String phoneNumber;
    private String password;
    private void doRegister() {
        showLoadingDialog(getString(R.string.dlg_msg_registing));
        dynamicCode = mVerifyCodeEt.getText().toString();
        phoneNumber = mPhoneNumberEditText.getText().toString();
        password = mPasswordEt.getText().toString();

        if( phoneNumber.trim().length() < 1){
            showErrorMsg("请输入手机号码");
            return ;
        }

        if(!LocalUtils.isPhoneNumber(phoneNumber)){
            LocalUtils.showToast(this, "手机号码不正确，请检查!");
            return ;
        }

        if( dynamicCode.trim().length() < 1){
            showErrorMsg(R.string.hint_inout_verify_code);
            return ;
        }

        if (!isVerifyCodeRight()) {
            showErrorMsg(R.string.verify_code_error);
            return;
        }

        if (password.trim().length() < 1) {
            showErrorMsg("请输入密码");
            return;
        }

        NetManager.getInstance(context).doRegister(phoneNumber, password, dynamicCode, new OnResponseListener<UserInfo>() {
            @Override
            public void onInternError(int errorCode, String errorMessage) {
                hideLoadingDialog();
                LocalUtils.showToast(RegisterActivity.this, errorMessage);
            }

            @Override
            public void onComplete(boolean b, UserInfo result, int i, String s) {
                hideLoadingDialog();
                if (b) {
                    LocalUtils.showToast(context, getString(R.string.register_success));
                    ((TianYaGongZaiApplication) getApplication()).exitAllActivity();
                    gotoUserInfoCollection();
                    finish();
                } else {
                    LocalUtils.showToast(RegisterActivity.this, s);
                }
            }
        });
    }

    /**
     * @Description 判断是否为6位验证码
     * @author xiezhidong251@jk.cn
     * @return
     */

    private boolean isVerifyCodeRight() {
        return mVerifyCodeEt.getText().toString().matches("\\d{6}");
    }


    /**
     * @Description 切换键盘
     * @author xiezhidong251@jk.cn
     */

    private void changeInputMethod() {
        mVerifyCodeEt.requestFocus();
    }

    /**
     * @Description 判断手机号码----再进行请求验证码
     * @return
     */
    private boolean doReqSmsCode() {
        phoneNumber = mPhoneNumberEditText.getText().toString();
        if(phoneNumber.trim().length() < 1){
            showErrorMsg(getString(R.string.phone_number_null));
            return false;
        }
        if (LocalUtils.isMobileNO(phoneNumber)) {
            doGetDynamicCode();
        } else {
            showErrorMsg(getString(R.string.label_invalid_phonenumber));
        }
        return true;
    }

    /**
     * @Description 请求短信
     * @author xiezhidong251@jk.cn
     */
    private boolean isRequestungDynamicCode = false;
    private void doGetDynamicCode() {
        if(isRequestungDynamicCode){
            showErrorMsg(R.string.toast_try_too_much);
            return ;
        }
        isRequestungDynamicCode = true;
        changeInputMethod();
//        mAskedPhoneNumber = phoneNumber;
        mHasSendCode = false;
        NetManager.getInstance(context).doRequestDynamicCode(phoneNumber, new OnResponseListener<Boolean>() {
            @Override
            public void onComplete(boolean b, Boolean result, int code, String errorMessage) {
                hideLoadingDialog();
                isRequestungDynamicCode = false;
                if (b) {
                    mHasSendCode = true;
                    showLoginButton();
                    LocalUtils.showToast(RegisterActivity.this, getString(R.string.verify_code_has_send_string));
                    mUIHandler.removeMessages(MSG_TIMER);
                    startCounter();
                } else {
                    LocalUtils.showToast(RegisterActivity.this, errorMessage);
                }
            }

            @Override
            public void onInternError(int errorCode, final String errorMessage) {
                hideLoadingDialog();
                isRequestungDynamicCode = false;
                LocalUtils.showToast(RegisterActivity.this, errorMessage);
            }
        });
    }


    /**
     * @Description 设置60秒倒计时
     */
    private void startCounter() {
        isVerifyCodeTime = true;
        mSendReqcodeBtn.setEnabled(false);
        mSendReqcodeBtn.setBackgroundResource(R.drawable.btn_rect_orange_fill);
        mSendReqcodeBtn.setTextColor(Color.WHITE);
        setVerifyCodeTime(60);
        sendTime(60);
    }

    /**
     * 设置动态验证过期时间
     * @param seconds
     */
    private void setVerifyCodeTime(int seconds) {
        if (seconds == 0) {
            mSendReqcodeBtn.setText(getString(R.string.req_dynamic_code));
            isVerifyCodeTime = false;
            return;
        }
        String time = String.format(getString(R.string.vefity_code_timer), seconds);
        mSendReqcodeBtn.setText(time);
    }

    private void sendTime(int seconds) {
        Message msg = mUIHandler.obtainMessage(MSG_TIMER, seconds, 0);
        mUIHandler.sendMessageDelayed(msg, 1000);
    }

}
